﻿using ChromeWebTool3;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyOTP2
{
    public class HuataiCloud
    {

        static BrowserAutomation Engine;

        static HuataiCloud()
        {

            Engine = new BrowserAutomation();
        }


        public static async Task Open(string userNameStr, string passwordStr, Func<string> GetkeyCodeStr, bool download)
        {
            if (!Engine.IsHasPage())
            {
                await Engine.InitStartChrome();
            }
            await Engine.NavigateToUrlAsync("https://cloud-kfs.htsc.com.cn/#/");
            await Engine.InputTextByXPathAsync("//*[@id=\"username\"]", userNameStr);
            await Engine.InputTextByXPathAsync("//*[@id=\"password\"]", passwordStr);
            var codekey = GetkeyCodeStr?.Invoke();
            await Engine.InputTextByXPathAsync("//*[@placeholder=\"令牌\"]", codekey);
            await Engine.ClickElementByXPathAsync("//*[@id=\"login\"]");

            if (download)
            {
                var downloadPath = await Engine.ClickElementByXPath_DownloadAsync("//*[@class=\"appDetails-actions-item\"]");
                //var downloadPath = await Engine.ClickElementByXPath_DownloadAsync("//*[@class=\"storeapp\"]");
                if (!string.IsNullOrEmpty(downloadPath)
                    && File.Exists(downloadPath))
                {
                    Process.Start("explorer.exe", $"/select,{downloadPath}"); //打开并选中
                    Process.Start(downloadPath);
                }

            }
        }
        public static async Task Dispose()
        {
            if (Engine != null)
            {
                await Engine.CloseAsync();
                //Engine = null;
            }
        }

    }
}
